﻿using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
using RHD.Common.Web.Utility.Extensions;

namespace RHD.Common.Web.Components {
	public static class InputExtension {
		public static MvcHtmlString Input(this HtmlHelper htmlHelper, string id, object value = null, object htmlAttributes = null) {
			return Input(htmlHelper, id, value, null, htmlAttributes);
		}

		public static MvcHtmlString InputFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null) {
			ModelMetadata model = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
			return Input(htmlHelper, ExpressionHelper.GetExpressionText(expression), model.Model, model, htmlAttributes);
		}

		private static MvcHtmlString Input(HtmlHelper htmlHelper, string id, object value = null, ModelMetadata modelMetadata = null, object htmlAttributes = null) {
			TagBuilder input = new TagBuilder("input");
			input.GenerateId(id);
			input.AddCssClass("form-control");
			input.Attributes["name"] = htmlHelper.GetFullHtmlFieldName(id);
			input.Attributes["type"] = "text";
			if (htmlAttributes != null)
				input.MergeAttributes<string, object>(new RouteValueDictionary(htmlAttributes));
			id = input.Attributes["id"];

			if (value != null)
				input.MergeAttribute("value", value.ToString(), true);

			MvcHtmlString validation = MvcHtmlString.Empty;
			if (modelMetadata != null) {
				input.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(modelMetadata.PropertyName, modelMetadata));
				validation = ValidationExtensions.ValidationMessage(htmlHelper, modelMetadata.PropertyName);
			}

			return new MvcHtmlString(string.Format("{0}{1}", input, validation));
		}
	}
}